package com.example.lanouhn.bantangapp.activities.activities;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lanouhn.bantangapp.R;
import com.example.lanouhn.bantangapp.activities.OnRecycleViewItemClickListenter;
import com.example.lanouhn.bantangapp.activities.adapters.Adapter_Activity_hottag;
import com.example.lanouhn.bantangapp.activities.adapters.Adapter_Search_history;
import com.example.lanouhn.bantangapp.activities.adapters.VpSelectedAdapter;
import com.example.lanouhn.bantangapp.activities.contants.MyEvent;
import com.example.lanouhn.bantangapp.activities.contants.Search_hottag;
import com.example.lanouhn.bantangapp.activities.contants.Search_hottag_url;
import com.example.lanouhn.bantangapp.activities.contants.Useroriginal;
import com.example.lanouhn.bantangapp.activities.fragments.Fragment_Deillist;
import com.example.lanouhn.bantangapp.activities.fragments.Fragment_Line;
import com.example.lanouhn.bantangapp.activities.fragments.Fragment_Thesun;
import com.example.lanouhn.bantangapp.activities.fragments.Fragment_Users;
import com.example.lanouhn.bantangapp.activities.utils.HttpUtils;
import com.example.lanouhn.bantangapp.activities.utils.JsonUtils_Search_hottag;
import com.example.lanouhn.bantangapp.activities.utils.SPUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lanouhn on 16/8/1.
 */
public class ActivitySearch_hottag extends FragmentActivity {

    private List<Search_hottag> hottaglists = new ArrayList<>();//实体类集合

    private Adapter_Activity_hottag adapter_activity_hottag;//recyclerview的adapter
    private RecyclerView recyclerView;
    private ImageView back;//返回
    private ImageView cancle;
    private EditText edittext;
    private boolean isVisible;//定义是否隐藏  默认是
    private LinearLayout ll_hottag;
    private LinearLayout ll_tog;//四个fragment
    private LinearLayout history_hot;//搜索历史和热门

    //private FrameLayout fragmenglayout;//用来替换的fragmentlayout

    private TabLayout tab;//tab头部
    private ViewPager vp;//vp部分

    private List<String> tabNames;
    //viewpager的数据集合
    private List<Fragment> fragments;
    //viewPager的适配器
    private VpSelectedAdapter vpfAdapter;

    private LinearLayout ll_history;//搜索历史记录
    private Adapter_Search_history historyadapter;//历史记录adapter
    private RecyclerView rehistory;//历史记录的recyclerview
    private TextView clear_history;//清除历史记录
    List<String> keyWordStrList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hottag);

        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        rehistory = (RecyclerView) findViewById(R.id.rehistory);//历史记录recyclerview控件
        back = (ImageView) findViewById(R.id.back);
        cancle = (ImageView) findViewById(R.id.cancle);
        edittext = (EditText) findViewById(R.id.edittext);
        ll_hottag = (LinearLayout) findViewById(R.id.ll_hottag);
        ll_tog = (LinearLayout) findViewById(R.id.ll_tog);
        ll_history = (LinearLayout) findViewById(R.id.ll_history);//搜索历史记录
        clear_history = (TextView) findViewById(R.id.clear_history);//清除历史记录


        tab = (TabLayout) findViewById(R.id.tab);
        vp = (ViewPager) findViewById(R.id.vp);
        initData();//添加数据
        setDataToView();//绑定数据到视图


        initDataToPost();
        initLinshener();


    }

    //数据集合
    private void initData() {
        //tab标签名称集合
        tabNames = new ArrayList();
        //Fragment集合
        fragments = new ArrayList();
        //tablayout数据集合
        tabNames.add(getResources().getString(R.string.Line));
        tabNames.add(getResources().getString(R.string.Deillist));
        tabNames.add(getResources().getString(R.string.sun));
        tabNames.add(getResources().getString(R.string.Users));

        // 添加页面
        fragments.add(new Fragment_Line());
        fragments.add(new Fragment_Deillist());
        fragments.add(new Fragment_Thesun());
        fragments.add(new Fragment_Users());

    }

    //绑定数据
    private void setDataToView() {
        vpfAdapter = new VpSelectedAdapter(getSupportFragmentManager(), tabNames, fragments);
        //设置适配器
        vp.setAdapter(vpfAdapter);
        vp.setOffscreenPageLimit(4);//设置vp缓存 暂存里面的fragment页面  左右两个

        //tabLayout和ViewPager绑定
        tab.setupWithViewPager(vp);
    }


    //监听点击事件
    private void initLinshener() {
        //返回
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //文本输入框编辑
        edittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, final int i, int i1, int i2) {
                if (edittext.getText().toString().trim().length() > 0) {
                    isVisible = false;
                    if (isVisible == false) {
                        cancle.setVisibility(View.VISIBLE);
                        isVisible = true;//这一句显示隐藏布局区域
                        //清除按钮
                        cancle.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(final View view) {
                                edittext.setText("");//清除数据
                                cancle.setVisibility(View.INVISIBLE);//隐藏清除按钮


                                //搜索历史
                                ll_history.setVisibility(View.VISIBLE);
                                ll_hottag.setVisibility(View.VISIBLE);
                                ll_tog.setVisibility(View.INVISIBLE);

                                //获取sharedpreference数据
                                //取出关键词
                                final String keyWordStr = (String) SPUtils.get(ActivitySearch_hottag.this, "history", "");
                                final String[] keyWords = keyWordStr.split(",");
                                //变换集合遍历取数据
                                keyWordStrList = new ArrayList<>();
                                for (String keywords : keyWords) {
                                    keyWordStrList.add(keywords);
                                }
                                //历史记录的adapter绑定
                                historyadapter = new Adapter_Search_history(ActivitySearch_hottag.this, keyWordStrList);
                                StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(5, LinearLayoutManager.VERTICAL);
                                rehistory.setLayoutManager(staggeredGridLayoutManager);
                                rehistory.setAdapter(historyadapter);
                                clear_history.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {

                                            SPUtils.clear(ActivitySearch_hottag.this);


                                        historyadapter.notifyDataSetChanged();
                                        ll_history.setVisibility(View.GONE);
                                    }
                                });


                            }
                        });

                    }
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
    }


    //post解析数据
    private void initDataToPost() {

        new Thread(new Runnable() {
            @Override
            public void run() {

                String url = Search_hottag_url.SEARCHhottagURL;//获取网络地址
                String params = "app_id=com.jzyd.BanTang&client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=2425199&oauth_token=dc743c52935a58a1391eab89d551e75c&track_deviceid=868596020655823&track_device_info=m2+note&channel_name=UMENG_CHANNEL&app_installtime=1468811189&app_versions=5.8.4&os_versions=5.1&screensize=1080&v=16";


                String result = HttpUtils.doPost(url, params);

                if (null != result && result.length() > 0) {
                    hottaglists = JsonUtils_Search_hottag.gethottagURL(result);
                    handler.sendEmptyMessage(1);
                } else {
                    handler.sendEmptyMessage(0);
                }

            }
        }).start();
    }

    //验证数据的线程
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    //失败
                    Toast.makeText(ActivitySearch_hottag.this, R.string.fail, Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    //成功
                    //绑定Adapter并在recyclerview上展示
                    adapter_activity_hottag = new Adapter_Activity_hottag(ActivitySearch_hottag.this, hottaglists);

                    recyclerView.setAdapter(adapter_activity_hottag);
                    StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(5, LinearLayoutManager.VERTICAL);
                    recyclerView.setLayoutManager(staggeredGridLayoutManager);

                    //调用adapter内定义的set方法
                    adapter_activity_hottag.setOnRecycleViewItemClickListenter(new OnRecycleViewItemClickListenter() {
                        @Override
                        public void OnClick(View view, int postion) {


                            //获取recyclerview的每个item
                            View view1 = recyclerView.getChildAt(postion);
                            TextView tv = (TextView) view1.findViewById(R.id.tv);
                            for (int i = 0; i < recyclerView.getChildCount(); i++) {
                                String item_tv = (String) tv.getText();

                                edittext.setText(item_tv);

                                //隐藏历史和热门
                                ll_hottag.setVisibility(View.INVISIBLE);
                                ll_history.setVisibility(View.INVISIBLE);
                                //打开热门清单、单品、晒单、用户页面
                                ll_tog.setVisibility(View.VISIBLE);
                            }
                            //搜索历史记录
                            //先获取原有的关键词
                            String oldKeyWord = (String) SPUtils.get(ActivitySearch_hottag.this, "history", "");
                            //获取现在的关键词
                            String keyWord = edittext.getText().toString();
                            //判断是是否保存过关键词
                            if (oldKeyWord.length() > 0) {

                                boolean flag = false;

                                //判断是否重复
                                String[] oldKWs = oldKeyWord.split(",");

                                for (int i = 0; i < oldKWs.length; i++) {
                                    if (oldKWs[i].equals(keyWord))
                                        flag = false;
                                    else
                                        flag = true;
                                }

                                //不重复
                                if (flag)
                                    //保存过， 拼接
                                    SPUtils.put(ActivitySearch_hottag.this, "history", oldKeyWord + "," + keyWord);

                            } else {
                                //未保存过，直接添加
                                SPUtils.put(ActivitySearch_hottag.this, "history", keyWord);
                            }


                            // EventBus 传递数据
                            EventBus.getDefault().post(new MyEvent(edittext.getText().toString()));
                        }
                    });

                    break;
            }
        }
    };


}
